import { userList } from '../db/testmodel.js';
import User from '../model/User.js';
import url from 'url';

async function dir(ctx, next) {
	// ctx.body = `<h1>首页</h1>`
	// select all user
	const users = await User.findAll();
	// console.log(users.every(user => user instanceof User)); // true
	// console.log("All users:", JSON.stringify(users, null, 2));
	ctx.render('Users.html',{users})
}

async function getusers(ctx, next) {

	const Urlp = url.parse(ctx.url, true); 		// 拿到页码和每页展示数
	console.log(Urlp);

	const page = Urlp.query.page || 1;		// Initialize page
	const limit = Urlp.query.limit || 5; 	// default Show page
	const totalPages = Math.ceil(userList.length / limit);	// All page
	const newuserList = [];	// Create newarrlist to retrun page

	// 判断请求数值是否有效
	if (page <= totalPages && limit <= userList.length) {
		const nowIndex = (page - 1) * limit;		// START
		let maxIndex = +nowIndex + +limit;		// END

		if (maxIndex > userList.length) {		// constraint length for userList 
			maxIndex = userList.length;
		}

		for (let i = nowIndex; i < maxIndex; i++) {		// retrun userlist
			newuserList.push(userList[i]);
		}

	} else {
		for (let i = 0; i < 5; i++) {		// Show first to fifth
			newuserList.push(userList[i]);
		}

		ctx.redirect(`/userList?page=1&limit=5`);		// Redirect
	}

	ctx.render("userList.html", { userList: newuserList });	//Userinfo render

}

async function userById(ctx, next) {
	const id = ctx.params.id;
	User.findAll({
		where:{

		}
	})
}

async function insertuser(ctx, next) {
	// Create User
	const user = await User.create(usercbj);

	ctx.render("adAndUp.html");
}

async function updateuser(ctx, next) {
	ctx.render("adAndUp.html");
}

async function deleteuser(ctx, next) {
	ctx.render("delete.html");
}


export const object = {
	"get@/": dir,
	"get@/users": getusers,
	"get@/users/:id": userById,
	"post@/usersAdd": insertuser,
	"put@/usersUpdate/:id": updateuser,
	"delete@/usersDelete/:id": deleteuser,
};